package com.itheima.controller;

import com.itheima.pojo.Employee;
import com.itheima.pojo.Login;
import com.itheima.pojo.User;
import com.itheima.service.LoginService;
import com.itheima.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/13 11:02
 * @Desc: 登录
 */
@RestController
@Slf4j
public class LoginController {
    @Autowired
    private LoginService loginService;

    /**
     * 系统后台登录
     *
     * @param employee
     * @param request
     * @return
     */
    @RequestMapping("/employee/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        employee = loginService.login(employee.getUsername(), employee.getPassword(), request);

        return employee != null ? R.success(employee) : R.error("登录失败");
    }

    /**
     * 系统后台退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/employee/logout")
    public R<String> exit(HttpServletRequest request) {
        request.getSession().removeAttribute("employeeId");

        return R.success("退出登录");
    }

    /**
     * 用户登录
     * @param login
     * @param request
     * @return
     */
    @PostMapping("/user/login")
    public R<String> login(@RequestBody Login login, HttpServletRequest request) {
        int i = loginService.login(login, request);

        return i == 1 ? R.success("登录成功") : R.error("登录失败");
    }

    /**
     * 发送短信验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/url/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        loginService.sendMsg(user.getPhone(), session);

        return R.success("发送成功");
    }

    /**
     * 用户退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/user/loginout")
    public R<String> userExit(HttpServletRequest request) {
        request.getSession().removeAttribute("userId");

        return R.success("退出登录");
    }
}
